package servlet;

import com.alibaba.fastjson.JSONObject;
import entity.GameRoom;
import entity.Player;
import entity.User;
import game.Z5CGame;
import service.*;
import top.RuntimeContextProvider;
import utils.Common;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;

@WebServlet(name = "playerServlet", urlPatterns = "*.player", loadOnStartup = 2)
public class PlayerServlet extends HttpServlet {

    private static WebsocketSessionService websocketSessionService =
            RuntimeContextProvider.getContextProvider().getWebsocketSessionService();
    private static PlayerService playerService =
            RuntimeContextProvider.getContextProvider().getPlayerService();
    private static UserService userService =
            RuntimeContextProvider.getContextProvider().getUserService();
    private static GameRoomService gameRoomService =
            RuntimeContextProvider.getContextProvider().getGameRoomService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        HttpSession userSession = req.getSession();

        switch(req.getServletPath()) {
            case "/regist.player": {
                //获取玩家的Websocket会话
                Session s = websocketSessionService.getAndRemoveWSSession(req.getParameter("wsSessionId"));
                if(s == null) break;

                //根据Servlet会话获取玩家的用户信息
                User u = userService.getUserInfo(userSession);
                if(u == null) break;

                //创建并注册玩家
                Player p = playerService.regist(userSession, s, u);
                if(p == null) break;

                //创建或加入房间
                //如果不是房主，隐藏并disable房间控制面板
                Object roomId = userSession.getAttribute("roomId");
                if(roomId != null) {
                    userSession.removeAttribute("roomId");
                    GameRoom gr = gameRoomService.getRoom(Long.parseLong((String) roomId));
                    if(gr != null) {
                        //加入房间
                        p.enterRoom(gr);
                        JSONObject json = new JSONObject();
                        json.put("type", "enterRoom");
                        json.put("roomTitle", gr.getTitle());
                        json.put("roomWatchable", gr.isWatchable());

                        //向挑战者发送房主的准备状态
                        if(gr.getReady() == 1) {
                            Player host = gr.getHost();
                            String hostPic = host.getUserInfo().getHeadPic();
                            if(Common.isStringEmpty(hostPic)) {
                                hostPic = "default";
                            }
                            if(host.getCamp() == Z5CGame.Camp.black) {
                                json.put("blackImg", hostPic);
                            } else {
                                json.put("whiteImg", hostPic);
                            }
                        } else if(gr.getReady() > 1) {//加入的是观众
                            Player host = gr.getHost();
                            Player challenger = gr.getChallenger();
                            String hostPic = host.getUserInfo().getHeadPic();
                            String chlgPic = challenger.getUserInfo().getHeadPic();

                            if(Common.isStringEmpty(hostPic)) hostPic = "default";
                            if(Common.isStringEmpty(chlgPic)) chlgPic = "default";

                            if(host.getCamp() == Z5CGame.Camp.black) {
                                json.put("blackImg", hostPic);
                                json.put("whiteImg", chlgPic);
                            } else {
                                json.put("whiteImg", hostPic);
                                json.put("blackImg", chlgPic);
                            }
                        }

                        resp.getWriter().write(json.toJSONString());
                        break;
                    }
                }
                //创建房间
                gameRoomService.createRoom("new room", p, null);
                resp.getWriter().write(Message.CREATE_ROOM);
                break;
            }
        }
    }
}
